package bootstrap

import (
	"23-viper/global"
	"fmt"

	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
)

func configAssemble[T any](configPath string, viperStruct T) *viper.Viper {
	v := viper.New()
	v.SetConfigFile(configPath)
	v.SetConfigType("yaml")
	if err := v.ReadInConfig(); err != nil {
		panic(fmt.Errorf("read config failed: %s", err))
	}

	v.WatchConfig()
	v.OnConfigChange(func(in fsnotify.Event) {
		fmt.Println("config file changed: ", in.Name)
		if err := v.Unmarshal(viperStruct); err != nil {
			fmt.Println(err)
		}
	})
	if err := v.Unmarshal(viperStruct); err != nil {
		fmt.Println(err)
	}
	return v
}

func InitializeConfig() {
	config := "config/files/config.yaml"
	configAssemble(config, &global.App.Config)
}
